﻿@using System.IO;
@using Tewr.Blazor.FileReader.DropEvents
@inject IFileReaderService fileReaderService
@inject IJSRuntime jsRuntime; 
<h1>Hello, dropped files!</h1>

Welcome to your new filestreaming app.
<br />
This demo is used for e2e tests.
<br />
<br />

<div id="drop-zone"
     @ref=dropTargetElement>

    Drop Files here.


    @foreach (var fileInfo in DropFileList)
    {
        <br />@fileInfo.Name
    }
</div>




<input id="additive" type="checkbox" checked=@Additive @onchange="OnAdditiveChange" /><label for="additive">Additive</label>
<br />
<input id="testDropEvents" type="checkbox" checked=@TestDropEvents @onchange="OnTestDropEvents" /><label for="testDropEvents">Test drop events</label>
<input id="testDropEventsValues" type="hidden"/>
<br />

<br />
<button @onclick="ReadDrop" class="btn btn-primary" id="read-file">Read file</button>
<button @onclick="ClearDrop" class="btn btn-primary">Clear</button>

<br />
<br />
<textarea id="debug-output" style="max-width: 100%;" cols="50" rows="20">@Output</textarea>
@code {
    ElementReference dropTargetElement;
    IFileReaderRef dropReference;
    bool Additive { get; set; }
    bool TestDropEvents { get; set; }
    bool TestDropEventsMethodsDefined;
    string Output { get; set; }
    List<IFileInfo> DropFileList { get; } = new List<IFileInfo>();

    protected override async Task OnAfterRenderAsync(bool isFirstRender)
    {
        if (isFirstRender)
        {
            dropReference = fileReaderService.CreateReference(dropTargetElement);
            await dropReference.RegisterDropEventsAsync();
        }
    }

    public async Task OnAdditiveChange(ChangeEventArgs e)
    {
        Additive = (bool)e.Value;
        StateHasChanged();
        await dropReference.UnregisterDropEventsAsync();
        await dropReference.RegisterDropEventsAsync(Additive);
    }

    public async Task OnTestDropEvents(ChangeEventArgs e)
    {
        TestDropEvents = (bool)e.Value;
        StateHasChanged();
        await dropReference.UnregisterDropEventsAsync();
        if (TestDropEvents)
        {
            if (!TestDropEventsMethodsDefined)
            {
                await jsRuntime.InvokeVoidAsync("eval",
                    @"window.testlog = (log, a, b, c) => 
                      { 
                            console.log(log, a, b, c); 
                            document.getElementById('testDropEventsValues').value = document.getElementById('testDropEventsValues').value + '\n'+ log; 
                      };

                     window.testondropovermethod = (a, b, c) => 
                            testlog('OnDropMethod', a, b, c);

                     window.testondragovermethod = (a, b, c) =>                       
                            testlog('OnDragOverMethod', a, b, c);
                ");

                TestDropEventsMethodsDefined = true;
            }

            await dropReference.RegisterDropEventsAsync(o => {
                o.SetDragOverDataTransferDropEffect(DropEffect.Copy);
                o.OnDragOverScript = $"(a,b,c) => {{ testlog('OnDragOverScript', a,b,c); ({o.OnDragOverScript})(a,b,c); }}";
                o.OnDropMethod = "testondropovermethod";
                o.OnDragOverMethod = "testondragovermethod";
                o.OnDropScript = "(a,b,c) => testlog('OnDropScript', a,b,c)";
            });
        }
        else
        {
            await dropReference.RegisterDropEventsAsync();
        }

    }

    public async Task ClearDrop()
    {
        await dropReference.ClearValue();
        await this.RefreshDropFileList();
    }

    private Task RefreshDropFileList()
    {
        return RefreshFileList(dropReference, DropFileList);
    }

    private async Task RefreshFileList(IFileReaderRef reader, List<IFileInfo> list)
    {
        list.Clear();
        foreach (var file in await reader.EnumerateFilesAsync())
        {
            var fileInfo = await file.ReadFileInfoAsync();
            list.Add(fileInfo);
        }
        this.StateHasChanged();
    }

    public async Task ReadDrop()
    {
        await ReadFile(dropReference);
    }

    public async Task ReadFile(IFileReaderRef list)
    {
        Output = string.Empty;
        this.StateHasChanged();
        var nl = Environment.NewLine;
        foreach (var file in await list.EnumerateFilesAsync())
        {
            var fileInfo = await file.ReadFileInfoAsync();
            Output += $"{nameof(IFileInfo)}.{nameof(fileInfo.Name)}: {fileInfo.Name}{nl}";

            using (var fs = await file.OpenReadAsync())
            {
                var bufferSize = 20480;
                var buffer = new byte[bufferSize];
                int count;
                while ((count = await fs.ReadAsync(buffer, 0, buffer.Length)) != 0)
                {
                    Output += $"Read {count} bytes. {fs.Position} / {fs.Length}{nl}";
                }
            }
            this.StateHasChanged();
        }
        Output += $"--DONE";

    }
}



